<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\facade\WeChat;
use app\common\facade\WeChatMini;
use app\common\model\Config;
use app\common\model\ContractLevel;
use app\common\model\Product;
use app\common\model\Business;
use app\common\model\ProductEvaluate;
use app\common\model\Relation;
use app\common\model\UserCollectBusiness;
use app\common\model\UserCollectProduct;
use app\common\model\UserLevel;
use app\common\model\UserNotify;
use app\common\model\UserProductDiscount;
use app\common\model\UserProductView;
use app\common\model\UserSignin;
use app\common\tool\Result;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Log;
use think\facade\View;
use app\common\model\User as UserModel;
use think\Response;
use app\common\model\Order;

class User extends Base
{
    /**
     * 小程序授权
     */
    public function authorization(): Response
    {
        try {
            $param = $this->request->post();
            $info = WeChatMini::session($param['code']);
            if (isset($info['errcode'])) {
                throw new \Exception('授权失败');
            }
            UserModel::update(['openid' => $info['openid']], ['id' => $this->user->id]);

        } catch (\Exception $e) {

            return Result::fail($e->getMessage());
        }

        return Result::success('授权成功');
    }

    public function index(): Response
    {
        $three_uid = Relation::where('uid', $this->user->id)->where('algebra', '<=', 3)->column('new_uid');
        //$leader_repeat_amount = Cache::get('system')['pool_ldc_open'] ? Cache::get('system')['leader_repeat_amount'] : 0;
        $leader_repeat_amount = 0;
        if(Cache::get('system')['pool_ldc_open']){
            if($this->user->syn_level >= 7){//区代或市代
                $leader_repeat_amount = Cache::get('system')['city_repeat_amount'];
            }elseif($this->user->syn_level == 6){//区代
                $leader_repeat_amount = Cache::get('system')['district_repeat_amount'];
            }elseif($this->user->syn_level == 5){//盟主
                $leader_repeat_amount = Cache::get('system')['leader_repeat_amount'];
            }
        }
        $bonus_reach = $this->user->my_leader_currm >= $leader_repeat_amount ? 1 : 0;
        $bonus_diff = $bonus_reach == 0 ? round($leader_repeat_amount - $this->user->my_leader_currm, 2) : 0;
        $result = [
            'account' => $this->user->account,
            'nickname' => $this->user->nickname ?? $this->user->mobile,
            'code' => $this->user->code,
            'mobile' => $this->user->mobile,
            'photo' => $this->user->photo ?? '/static/api/img/default_avatar.png',
            'level_id' => $this->user->level_id,
            'level' => $this->user->level ? $this->user->level->title : '',
            'syn_level' => $this->user->syn_level,
            'flag_id' => $this->user->level_flag_id,
            'flag' => $this->user->flag ? $this->user->flag->title : '',
            'level_video_id' => $this->user->level_video_id,
            'level_video' => $this->user->video ? $this->user->video->title : '',
            'breed' => $this->user->breed ? $this->user->breed->title : '',
            'contract_level' => $this->user->contract ? $this->user->contract->title : '',
            'contract_role' => $this->user->contract_role_id ? contractRole($this->user->contract_role_id) : '',
            'parent_code' => $this->user->parent_code ?: '',
            'agent_city' => $this->user->agent_level == 2 || $this->user->agent_level == 3 ? '市代' : '',
            'agent_district' => $this->user->agent_level == 1 || $this->user->agent_level == 3 ? '区代' : '',
            'pasture_city' => $this->user->pasture_agent_level == 2 || $this->user->pasture_agent_level == 3 ? '市代' : '',
            'pasture_district' => $this->user->pasture_agent_level == 1 || $this->user->pasture_agent_level == 3 ? '区代' : '',
            'contract_city' => $this->user->contract_agent_level == 2 || $this->user->contract_agent_level == 3 ? '市代' : '',
            'contract_district' => $this->user->contract_agent_level == 1 || $this->user->contract_agent_level == 3 ? '区代' : '',
            'business_id' => $this->user->business_id,
            'real_status' => $this->user->real_status,
            'real_name' => $this->user->real_name,
            'idcard' => $this->user->idcard,
            'birthday' => $this->user->birthday,
            'wechat_name' => $this->user->wechat_name,
            'wechat_image' => $this->user->wechat_image,
            'alipay_name' => $this->user->alipay_name,
            'alipay_image' => $this->user->alipay_image,
            'bank_name' => $this->user->bank_name,
            'bank_open' => $this->user->bank_open,
            'bank_account_name' => $this->user->bank_account_name,
            'bank_number' => $this->user->bank_number,
            'face_image' => $this->user->face_image,
            'share' => $this->request->domain() . "/api/register/web.html?code=" . $this->user['code'],
            'product_count' => UserCollectProduct::where(['uid' => $this->user->id, 'is_del' => 0])->count(),//收藏（商品数量）
            'business_count' => UserCollectBusiness::where(['uid' => $this->user->id, 'is_del' => 0])->count(),//关注（店铺数量）
            'view_count' => UserProductView::where(['uid' => $this->user->id, 'is_del' => 0])->count(),//足迹
            'discount_count' => UserProductDiscount::where(['uid' => $this->user->id, 'status' => 1, 'is_del' => 0])->count(),//折扣券
            'exp_time' => $this->user->expire_time ? $this->user->expire_time : UserModel::getExpTime($this->user),
            'consume_month' => Order::where(['uid' => $this->user->id])->whereMonth('pay_time')->sum('real_amount'),
            'consume_total' => $this->user->consume_total,
            'consume_team' => Order::whereIn('uid', $three_uid)->where('pay_time', '>', 0)->sum('real_amount'),
            'bonus_reach' => $bonus_reach,
            'bonus_diff' => $bonus_diff,
            'tillage' => $this->user->tillage ? $this->user->tillage->title : '',
            'tillage_city' => $this->user->tillage_agent_level == 2 || $this->user->tillage_agent_level == 3 ? '市代' : '',
            'tillage_district' => $this->user->tillage_agent_level == 1 || $this->user->tillage_agent_level == 3 ? '区代' : '',

            'village_business_id' => $this->user->village_business_id,
            'village_city' => $this->user->village_agent_level == 2 || $this->user->village_agent_level == 3 ? '市代' : '',
            'village_district' => $this->user->village_agent_level == 1 || $this->user->village_agent_level == 3 ? '区代' : '',
            'village_bao' => $this->user->assets->village_bao,
            'village_piao' => $this->user->assets->village_piao,
            'village_lian' => $this->user->assets->village_lian,
            'village_fen' => $this->user->assets->village_fen,
            'village_forecast' => 0,//VillageRelease::getForecast($this->user->id),
            'village_id' => $this->user->village_id,
            'village' => $this->user->village ? $this->user->village->title : '',
        ];

        return Result::success('success', $result);
    }

    public function setting()
    {
        return View::fetch();
    }

    /**
     * 云牧场-我的团队
     */
    public function pastureMyTeam(): Response
    {
        $map = ['uid' => $this->user->id, 'algebra' => 1];
        $list = Relation::getPageList($map, 'uid,new_uid', $this->getPage(), $this->getLimit(), false, ['fresh']);
        foreach ($list['data'] as &$v) {
            $v->code = $v->fresh->code;
            $v->nickname = $v->fresh->nickname;
            $v->mobile = $v->fresh->mobile;
            $v->breed = $v->fresh->breed ? $v->fresh->breed->title : '无';
            unset($v->uid);
            unset($v->new_uid);
            unset($v->fresh);
        }

        return Result::fastReturn($list);
    }

    /**
     * 云耕科技-我的团队
     */
    public function tillageMyTeam(): Response
    {
        $map = ['uid' => $this->user->id, 'algebra' => 1];
        $list = Relation::getPageList($map, 'uid,new_uid', $this->getPage(), $this->getLimit(), false, ['fresh']);
        foreach ($list['data'] as &$v) {
            $v->code = $v->fresh->code;
            $v->nickname = $v->fresh->nickname;
            $v->mobile = $v->fresh->mobile;
            $v->tillage = $v->fresh->tillage ? $v->fresh->tillage->title : '无';
            unset($v->uid);
            unset($v->new_uid);
            unset($v->fresh);
        }

        return Result::fastReturn($list);
    }

    /**
     * 乡村振兴-我的团队
     */
    public function villageMyTeam(): Response
    {
        $map = ['uid' => $this->user->id, 'algebra' => 1];
        $list = Relation::getPageList($map, 'uid,new_uid', $this->getPage(), $this->getLimit(), false, ['fresh']);
        foreach ($list['data'] as &$v) {
            $v->code = $v->fresh->code;
            $v->nickname = $v->fresh->nickname;
            $v->mobile = $v->fresh->mobile;
            //$v->village = $v->fresh->village ? $v->fresh->village->title : '无';
            unset($v->uid);
            unset($v->new_uid);
            unset($v->fresh);
        }

        return Result::fastReturn($list);
    }

    /**
     * 修改个人信息
     */
    public function edit(): Response
    {
        $param = $this->request->post('', '', $this->filter);
        $result = UserModel::_miniAppletEdit($param, $this->user);
        if ($result['code'] == 1) {
            return Result::success($result['msg']);
        }

        return Result::fail($result['msg']);
    }

    public function notify($type)
    {
        $param = $this->request->param();
        if ($type == 1) {
            $count = UserNotify::where(['uid' => $this->user->id, 'is_read' => 0])->count();
            return json(['code' => 1, 'msg' => 'success', 'result' => $count]);
        } else {
            $map = ['uid' => $this->user->id, 'is_del' => 0];
            return json(UserNotify::getPageList($map, 'id,type,content,is_read,create_time', $param['page'], 20, false));
        }
    }

    /**
     * 签到
     */
    public function signIn(): Response
    {
        $result = UserSignin::add($this->user);
        if ($result['code'] == 1) {
            return Result::fastReturn($result);
        }
        return Result::fail($result['msg']);
    }

    /**
     * 签到记录
     */
    public function signInList(): Response
    {
        $month = $this->request->param('month', date("Y-m"));
        $list = UserSignin::signInList($this->user, $month);
        return Result::fastReturn($list);
    }

    /**
     * 签到周期
     */
    public function signInCycle(): Response
    {
        $result = UserSignin::cycle($this->user);
        return Result::fastReturn($result);
    }

    /**
     * 我的足迹
     * @return Response
     */
    public function foot(): Response
    {
        $list = UserProductView::foot($this->user);
        return Result::fastReturn($list);
    }

    /**
     * 我的收藏
     * @return Response
     */
    public function collectProduct(): Response
    {
        $pids = UserCollectProduct::where(['uid' => $this->user->id, 'is_del' => 0])->column('pid');

        $list = Product::where(['is_del' => 0, 'status' => 1])->whereIn('id', $pids)->field('id,title,price,vip_price,icon')
            ->order('create_time', 'desc')->paginate($this->getLimit());

        $result = ['code' => 1, 'msg' => 'success', 'data' => $list];
        return Result::fastReturn($result);
    }

    /**
     * 我的关注
     * @return Response
     */
    public function collectBusiness(): Response
    {
        $bids = UserCollectBusiness::where(['uid' => $this->user->id, 'is_del' => 0])->column('business_id');

        $list = Business::where(['is_del' => 0, 'status' => 1])->whereIn('id', $bids)->field('id,title,logo,fans,products,describe_score')->
        withCount(['products'])->order('create_time', 'desc')->paginate($this->getLimit())->each(function ($item) {
            $item->products = $item->products_count;//。。。
        });

        $result = ['code' => 1, 'msg' => 'success', 'data' => $list];

        return Result::fastReturn($result);
    }

    /**
     * 我的评论
     * @return Response
     */
    public function productEvaluate(): Response
    {
        $map = [
            'uid' => $this->user->id,
        ];
        $field = 'id,pid,uid,content,images,score,create_time,status,business_id,order_id,order_product_id,reply_content,reply_time,reply_admin_id,reply_admin_name';
        $with = ['product', 'user'];
        $list = ProductEvaluate::getPageList($map, $field, $this->getPage(), $this->getLimit(), false, $with);
        return Result::fastReturn($list);
    }

    /**
     * 我的团队
     * @return Response
     */
    public function myTeam(): Response
    {
        $month = $this->request->param('month', date("Y-m"));
        $teamIds = Relation::where('uid', $this->user->id)->column('new_uid');

        $top = [
            'team_total' => $this->user->team_total,
            'team_dedicate' => $this->user->team_dedicate,
            'team_count' => count($teamIds),
            'rec_score' => $this->user->rec_score
        ];

        $level = UserLevel::column('title', 'id');
        $total = UserModel::whereIn('id', $teamIds)->group('level_id')->column('count(id) as total', 'level_id');
        $new = UserModel::whereIn('id', $teamIds)->whereMonth('create_time', $month)->group('level_id')->column('count(id) as total', 'level_id');
        $direct = UserModel::where('parent_id', $this->user->id)->group('level_id')->column('count(id) as total', 'level_id');

        $count = [];
        foreach ($level as $id => $title) {
            $count[$id] = [
                'level_id' => $id,
                'title' => $title,
                'total' => isset($total[$id]) ? $total[$id] : 0,
                'new' => isset($new[$id]) ? $new[$id] : 0,
                'direct' => isset($direct[$id]) ? $direct[$id] : 0,
            ];
        }

        $data = [
            'top' => $top,
            'count' => array_values($count)
        ];

        return Result::fastReturn(['code' => 1, 'msg' => 'success', 'data' => $data]);
    }

    /**
     * 我的团队列表
     * @return Response
     */
    public function myTeamList(): Response
    {
        $type = $this->request->param('type', 1);
        $level = $this->request->param('level', 1);

        $direct_count = Relation::where(['uid' => $this->user->id, 'algebra' => 1])->count();
        $indirect_count = Relation::where(['uid' => $this->user->id])->where('algebra', 2)->count();

        $listRows = [
            'page' => $this->getPage(),
            'list_rows' => $this->getLimit()
        ];
        $tag = [1 => '普通会员', 2 => 'VIP会员', 3 => '店主', 5 => '盟主', 6 => '区代', 7 => '市代'];
        $contract = ContractLevel::column('title', 'id');
        $list = Relation::with(['fresh'])->when($level, function ($query) use ($level) {
            if ($level == 3) {
                $where = [['level_id', 'in', [3, 4]]];
            } elseif ($level == 6) {
                $where = [['agent_level', 'in', [1, 3]]];
            } elseif ($level == 7) {
                $where = [['agent_level', 'in', [2, 3]]];
            } else {
                $where = ['level_id' => $level];
            }
            $query->hasWhere('fresh', $where);
        })->where('uid', $this->user->id)->when($type, function ($query) use ($type) {
            if ($type == 1) {
                $query->where('algebra', 1);
            } else {
                $query->where('algebra', 2);
            }
        })->field('uid,new_uid')->paginate($listRows)->each(function ($item) use ($tag, $level, $contract) {
            $item->uid = $item->fresh->id;
            $item->code = $item->fresh->code;
            $item->nickname = $item->fresh->nickname;
            $item->mobile = $item->fresh->mobile;
            $item->photo = $item->fresh->photo;
            $item->my_total = $item->fresh->my_total;
            $item->my_dedicate = $item->fresh->my_dedicate;
            $item->level = isset($tag[$level]) ? $tag[$level] : '';
            $item->contract_level = isset($contract[$item->fresh->contract_level_id]) ? $contract[$item->fresh->contract_level_id] : '';
            unset($item->id, $item->status, $item->first_uid, $item->first_code, $item->new_code, $item->algebra, $item->create_time, $item->update_time, $item->new_uid, $item->fresh);
        })->toArray();

        $list['count'] = [
            'direct_count' => $direct_count,
            'indirect_count' => $indirect_count,
        ];

        return Result::success('success', $list);
    }

    /**
     * 我的合约团队
     * @return Response
     */
    public function myContractTeam(): Response
    {
        $month = $this->request->param('month', date("Y-m"));
        $teamIds = Relation::where('uid', $this->user->id)->column('new_uid');

        $top = [
            'team_total' => $this->user->team_total,
            'team_dedicate' => $this->user->team_dedicate,
            'team_count' => count($teamIds)
        ];

        $level = ContractLevel::column('title', 'id');
        $total = UserModel::whereIn('id', $teamIds)->where('contract_role_id', '>', 0)->group('contract_level_id')->column('count(id) as total', 'contract_level_id');
        $new = UserModel::whereIn('id', $teamIds)->where('contract_role_id', '>', 0)->whereMonth('create_time', $month)->group('contract_level_id')->column('count(id) as total', 'contract_level_id');
        $direct = UserModel::where('parent_id', $this->user->id)->group('contract_level_id')->column('count(id) as total', 'contract_level_id');

        $count = [];
        foreach ($level as $id => $title) {
            $count[$id] = [
                'level_id' => $id,
                'title' => $title,
                'total' => isset($total[$id]) ? $total[$id] : 0,
                'new' => isset($new[$id]) ? $new[$id] : 0,
                'direct' => isset($direct[$id]) ? $direct[$id] : 0,
            ];
        }

        $data = [
            'top' => $top,
            'count' => array_values($count)
        ];

        return Result::fastReturn(['code' => 1, 'msg' => 'success', 'data' => $data]);
    }

    /**
     * 我的合约团队列表
     * @return Response
     */
    public function myContractTeamList(): Response
    {
        $type = $this->request->param('type', 1);
        $direct_count = Relation::with(['fresh'])->when(true, function ($query) {
            $where = [['contract_role_id', '>', 0]];
            $query->hasWhere('fresh', $where);
        })->where(['uid' => $this->user->id, 'algebra' => 1])->count();
        $indirect_count = Relation::with(['fresh'])->when(true, function ($query) {
            $where = [['contract_role_id', '>', 0]];
            $query->hasWhere('fresh', $where);
        })->where(['uid' => $this->user->id])->where('algebra', 2)->count();

        $listRows = [
            'page' => $this->getPage(),
            'list_rows' => $this->getLimit()
        ];
        $contract = ContractLevel::column('title', 'id');
        $list = Relation::with(['fresh'])->when(true, function ($query) {
            $where = [['contract_role_id', '>', 0]];
            $query->hasWhere('fresh', $where);
        })->when($type, function ($query) use ($type) {
            if ($type == 1) {
                $query->where('algebra', 1);
            } else {
                $query->where('algebra', 2);
            }
        })->where('uid', $this->user->id)->field('uid,new_uid')->paginate($listRows)->each(function ($item) use ($contract) {
            $item->uid = $item->fresh->id;
            $item->code = $item->fresh->code;
            $item->nickname = $item->fresh->nickname;
            $item->mobile = $item->fresh->mobile;
            $item->photo = $item->fresh->photo;
            $item->my_total = $item->fresh->my_total;
            $item->my_dedicate = $item->fresh->my_dedicate;
            $item->team_dedicate = $item->fresh->team_dedicate;
            $item->contract_level = isset($contract[$item->fresh->contract_level_id]) ? $contract[$item->fresh->contract_level_id] : '';
            unset($item->id, $item->status, $item->first_uid, $item->first_code, $item->new_code, $item->algebra, $item->create_time, $item->update_time, $item->new_uid, $item->fresh);
        })->toArray();

        $list['count'] = [
            'direct_count' => $direct_count,
            'indirect_count' => $indirect_count,
        ];

        return Result::success('success', $list);
    }

    /**
     * 消费排行榜
     * @return Response
     */
    public function ranking(): Response
    {
        $uids = Relation::where('uid', $this->user->id)->where('algebra', '<=', 3)->column('new_uid');
        $in = ['id' => $uids];
        $sort = [
            'key' => 'my_total',
            'value' => 'desc'
        ];
        $list = UserModel::getPageList([], 'id,nickname,real_name,photo,my_total', $this->getPage(), $this->getLimit(), false, [], $in, $sort);

        return Result::fastReturn($list);
    }

    /**
     * 消费会员
     * is_consume
     * @param int $is_consume 1已消费 0未消费
     * @return Response
     */
    public function consumeUser($is_consume = 1): Response
    {
        $query = UserModel::where('parent_id', $this->user->id);

        $yes = UserModel::where('parent_id', $this->user->id)->where('my_total', '>', 0)->count();
        $not = UserModel::where('parent_id', $this->user->id)->where('my_total', '0.00')->count();
        $total = $yes + $not;

        $yes_rate = $total > 0 ? round($yes / $total, 2) : 0;
        $not_rate = round(1 - $yes_rate, 2);
        if ($is_consume) {
            $query->where('my_total', '>', 0);
        } else {
            $query->where('my_total', 0);
        }

        $list = $query->with(['level' => function ($query) {
            $query->field('id,title');
        }])->field('id,mobile,photo,nickname,real_name,level_id,my_total')->page($this->getPage(), $this->getLimit())->select();

        $data = [
            'rate' => [
                'yes' => $yes,
                'not' => $not,
                'total' => $total,
                'yes_rate' => ($yes_rate * 100) . '%',
                'not_rate' => ($not_rate * 100) . '%',
            ],
            'list' => $list
        ];

        $result = ['code' => 1, 'msg' => 'success', 'data' => $data];

        return Result::fastReturn($result);
    }

    /**
     * 客服电话
     * @return Response
     */
    public function service(): Response
    {
        $service_tel = Config::where('name', 'service_tel')->value('value');
        $result = ['code' => 1, 'msg' => 'success', 'data' => ['service_tel' => $service_tel]];

        return Result::fastReturn($result);
    }

    /**
     * 实名认证
     * name 真实姓名
     * idcard 身份证号
     * @return Response
     */
    public function realAuth(): Response
    {
        $param = $this->request->param();

        try {
            $this->validate($param, 'RealAuth');
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        }

        return Result::fastReturn(UserModel::realAuth($this->user, $param));
    }

    /**
     * 上传人脸照
     * @param string $face_image
     * @return Response
     */
    public function uploadFaceImage(string $face_image): Response
    {
        if (!$face_image) {
            return Result::fail('人脸照不能为空');
        }
        $this->user->face_image = $face_image;
        $this->user->save();

        return Result::success('上传成功');
    }

    /**
     * 抵扣券
     * status ：1未使用2已使用3已过期
     * @return Response
     */
    public function discount(): Response
    {
        $status = $this->request->param('status', 1);
        $map = ['uid' => $this->user->id, 'status' => $status];
        $result = UserProductDiscount::getPageList($map, 'pid,amount,create_time,expire_time,use_time,status,explain,sn', $this->getPage(), $this->getLimit(), false, [], [], [], [], [], '', ['create_date', 'expire_date']);

        return Result::fastReturn($result);
    }

    /**
     * 分享码
     * @return Response
     */
    public function qrcode(): Response
    {
        $share = "/api/register/web.html?code=" . $this->user['code'];
        return Result::fastReturn(['code' => 1, 'msg' => 'success', 'data' => ['qrcode' => $share]]);
    }

    /**
     * 我的消息
     * @return Response
     */
    public function myNotify(): Response
    {
        try {
            $list_rows = [
                'page' => $this->getPage(),
                'list_rows' => $this->getLimit()
            ];

            $list = UserNotify::where('uid', $this->user->id)
                ->field('id,uid,type,title,content,is_read,create_time')
                ->order('id', 'desc')
                ->paginate($list_rows)
                ->each(function ($item) {
                    $item->is_read = 1;
                    $item->save();
                });
            return Result::success('success', $list);
        } catch (\Exception $e) {
            return Result::fail('服务器错误');
        }
    }

    /**
     * 修改手机号
     * @return Response
     */
    public function changeMobile(): Response
    {
        try {
            $param = $this->request->param();
            $this->validate($param, 'ChangeMobile');
            if ($param['old_mobile'] != $this->user->mobile) {
                return Result::fail('原手机号输入错误！');
            }
            $old_code = Cache::get('yusheng250124:' . $param['old_mobile']);
            if ($old_code != $param['old_code']) {
                return Result::fail('原手机号验证码错误！');
            }
            $new_code = Cache::get('yusheng250124:' . $param['new_mobile']);
            if ($new_code != $param['new_code']) {
                return Result::fail('新手机号验证码错误！');
            }

            $this->user->mobile = $param['new_mobile'];
            $this->user->save();

            return Result::success('修改成功');
        } catch (\Exception $e) {
            return Result::fail('服务器错误');
        }
    }

    public function openCancel(): Response
    {
        $open = Cache::get('system')['open_cancel'];
        return Result::success('success', ['open' => $open]);
    }

    public function cancel(): Response
    {
        $this->user->is_del = 1;
        $this->user->token = '';
        $this->user->save();

        return Result::success('注销成功');
    }

    /**
     * 静默授权获取公众号openid（需配置授权域名）
     */
    /*public function gzhOpenid()
    {
        if (!isset($_GET['code'])) {
            $redirectUri = $this->request->domain().'/api/user/getGzhOpenid';
            $url = WeChat::getOauthRedirect($redirectUri, '', 'snsapi_base');
            header("Location:" . $url);
            exit;
        }
        return View::fetch('gzh');
    }*/

    /*public function getGzhOpenid()
    {
        try {
            $code = $this->request->param('code');
            if (!empty($code)) {
                $res = WeChat::getOauthAccessToken($code);
                Log::write("getGzhOpenid:".json_encode($res, JSON_UNESCAPED_UNICODE));
                if (isset($res['openid'])) {
                    return Result::success('获取成功！', $res);
                } else {
                    return Result::fail('服务器错误！');
                }
            } else {
                return Result::fail('请重新获取授权！');
            }
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }

    }

    public function bindGzhOpenid()
    {
        if(!$openid = $this->request->param('openid')){
            return Result::fail('获取公众号openid失败');
        }
        $this->user->save(['ghz_openid'=>$openid]);

        return Result::success('success');
    }*/

    //乡村振兴 - 预估收益
    public function villageReleaseRecord()
    {
        $list = VillageRelease::where(['uid'=>$this->user->id, 'is_del'=>0])->field('id,uid,sn,total_profit,daily_profit,profit_days,profited_days,released,surplus,status,create_time')
            ->order('id', 'desc')->paginate($this->getLimit());

        $data = [
            'list' => $list->items(),
            'total' => $list->total()
        ];
        return Result::success('success', $data);
    }

}

